var app = getApp();
var md5 = require('../../../libs/md5.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    end: [],
    start: [],
    showtime:false,
    id:'',
    dataObj:{},
    shopid:'',
    checked:false,
    mden: false,

  },
  // 初始化活动日期
  initDate(){
    let time=[];
    for(let i = 0;i<=24;i++){
      let str = i + '0:00';
      if(i< 10){
          str = '0' + String(i) + ':00'
      }else{
        str = i + ':00';
      }
      
      time.push(str)
    }
    console.log(time)
    this.setData({
      end:time,
      start:time
    })
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initDate()
    this.setData({
      shopid:wx.getStorageSync('shop_id')
    })
    this.getshop();
    this.getinfo()
  },
  /**
 * 生命周期函数--监听页面显示
 */
  onShow: function () {

  },
  submitform:function(e){
     console.log(e)
     console.log(this.data.checked)
     if(!this.data.checked){
      wx.showToast({
        title: '请同意商家入驻协议',
        icon:'none'
      })
      return
     }
     let obj = this.data.dataObj;
     if(!obj.mentou.length){
      wx.showToast({
        title: '请上传门头照片',
        icon:'none'
      })
      return
     }
     if(!obj.yingye.length){
      wx.showToast({
        title: '请上传营业执照或身份证',
        icon:'none'
      })
      return
     }
     let params = e.detail.value;
     for(let k in params){
       if(k === 'bank_name' || k === 'bank_number' || k === 'bank_user'){
         continue;
       }
       if(!params[k]){
         wx.showToast({
           title: '请完善商家基本信息',
           icon:'none'
         })
         return
       }
     }
     params.mentou = obj.mentou.join(',');
     params.yingye = obj.yingye.join(',');
     params.shop_id = this.data.shopid
     app.post({
       url:'api/shopr/reviewEditShop',
       data:params,
       success:e=>{
          let res = e.data;
          console.log(res)
          wx.showToast({
            title: '已提交成功，尽快为您审核',
            icon:'none'
          })
          this.getshop()
       }
     })
  },
  // 获取商家默认信息
  getshop(){
       app.post({
         url:"api/shopr/getEditInfo",
         data:{
           shop_id:this.data.shopid
         },
         success:e=>{
           console.log(res)
           let res = e.data.data;
           if(res.review_status == 1){
             wx.showModal({
               title:'提示',
               content:"信息正在审核中...",
               showCancel:false,
             })
           }
           if(res.review_status == 2){
            wx.showModal({
              title:'提示',
              content:"信息审核失败",
              showCancel:false,
            })
          }
           this.setData({
             mden:true,
             dataObj:res
           })
         }
       })  
      
  },
  chooseimgs1: function(e){
    var that = this;
    let dataObj = that.data.dataObj;
    var images = dataObj.mentou;
    var timestamp = Date.parse(new Date()) / 1000;
    var random = Math.floor(Math.random() * 100);
    var sign = 'GHRDY65' + String(random) + String(timestamp);
    sign = md5.hexMD5(sign);
    wx.chooseImage({
      count: 6 - images.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        for (var i = 0; i < res.tempFilePaths.length; i++) {
          wx.uploadFile({
            url: app.static.url + 'api/common/uploadFile',
            filePath: res.tempFilePaths[i],
            name: 'file',
            formData: {
              timestamp: timestamp,
              random: random,
              sign: sign
            },
            success: function (ret) {
              var data = ret.data;
              data = JSON.parse(data);
              dataObj.mentou = dataObj.mentou.concat(data.data.url)
              if (data.code == 1) {
                that.setData({
                  dataObj: dataObj,
                });
              }
            }
          })
        }
      }
    })
  },
  chooseimgs2: function (e) {
    var that = this;
    let dataObj = that.data.dataObj;
    var images = dataObj.yingye;
    var timestamp = Date.parse(new Date()) / 1000;
    var random = Math.floor(Math.random() * 100);
    var sign = 'GHRDY65' + String(random) + String(timestamp);
    sign = md5.hexMD5(sign);
    wx.chooseImage({
      count: 2 - images.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        for (var i = 0; i < res.tempFilePaths.length; i++) {
          wx.uploadFile({
            url: app.static.url + 'api/common/uploadFile',
            filePath: res.tempFilePaths[i],
            name: 'file',
            formData: {
              timestamp: timestamp,
              random: random,
              sign: sign
            },
            success: function (ret) {
              var data = ret.data;
              data = JSON.parse(data);
              dataObj.yingye = dataObj.yingye.concat(data.data.url)
              if (data.code == 1) {
                that.setData({
                  dataObj: dataObj,
                });
              }
            }
          })
        }
      }
    })
  },
  
  delimg: function (e) {
    var that = this;
    let param = e.currentTarget.dataset;
    console.log(param)
    wx.showModal({
      title: '提醒',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          let dataObj = that.data.dataObj;
          let imgs = param.type ? dataObj.mentou : dataObj.yingye;
          imgs.splice(param.index, 1)
          
          if(param.type){
            dataObj.mentou = imgs
          }else{
            dataObj.yingye = imgs
          }
          that.setData({
            dataObj: dataObj,
          });
        } 
      }
    })
  },
  // 选择时间
  stime: function () {
    this.setData({
      showtime: 1,
      starttime: this.data.start[0],
      endtime: this.data.end[0],
    })
   
  },
  hidetime:function(){
    this.setData({
      showtime: 0,
    })
  },
  timeChange: function (e) {
    var val = e.detail.value;
    let dataObj = this.data.dataObj;
    dataObj.start_time = this.data.start[val[0]];
    dataObj.end_time = this.data.end[val[1]]
    this.setData({
      dataObj:dataObj
    })
  },
  
  /**********用户地址选择**********/
  location: function () {
    this.getUserLocation();
  },

  /********用户授权********/
  getUserLocation: function () {
    let that = this
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          // console.log('authSetting:status:拒绝授权后再次进入重新授权', res.authSetting['scope.userLocation'])
          wx.showModal({
            title: '',
            content: '我们需要获取你的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none'
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    // console.log('dataAu:success', dataAu)
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      //再次授权，调用wx.getLocation的API
                      that.getLocation(dataAu)
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none'
                      })
                    }
                  }
                })
              }
            }
          })
        }
        // 初始化进入，未授权
        else if (res.authSetting['scope.userLocation'] == undefined) {
          that.getLocation(res)
        }
        // 已授权
        else if (res.authSetting['scope.userLocation']) {
          that.getLocation(res)
        }
      }
    })
  },
  // 微信获得经纬度
  getLocation: function (userLocation) {
    let that = this
    wx.getLocation({
      type: "wgs84",
      success: function (res) {
        // console.log('getLocation:success', res)
        var latitude = res.latitude
        var longitude = res.longitude
        that.moveToLocation();
      },
      fail: function (res) {
        // console.log('getLocation:fail', res)
        if (res.errMsg === 'getLocation:fail:auth denied') {
          wx.showToast({
            title: '拒绝授权',
            icon: 'none'
          })
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
          return
        }
        if (!userLocation || !userLocation.authSetting['scope.userLocation']) {
          that.getUserLocation()
        } else if (userLocation.authSetting['scope.userLocation']) {
          wx.showModal({
            title: '',
            content: '请在系统设置中打开定位服务',
            showCancel: false,
            success: result => {
              if (result.confirm) {
                wx.navigateBack()
              }
            }
          })
        } else {
          wx.showToast({
            title: '授权失败',
            icon: 'none'
          })
        }
      }
    })
  },
  // 
  //移动选点
  moveToLocation: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        if (res.name != '') {
          let dataObj = that.data.dataObj;
          dataObj.address = res.name;
          dataObj.latitude = res.latitude;
          dataObj.longitude = res.longitude;
          that.setData({
            dataObj:dataObj
          })
        }

      },
      fail: function (err) {
        console.log(err);
        wx.navigateBack({
          delta: 1
        });
      }
    });
  },
  // 获取服务协议
  getinfo:function(){
    var that = this;
    var param = {
      url:"api/shop/getArticles",
      success:function(e){
        var data = e.data.data;
        console.log(data)
      
      }
    };
    app.post(param);
  },
  xuzhi:function(){
    this.setData({
      checked:!this.data.checked
    })
  }
})